package com.jyu.work.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jyu.common.context.BaseContext;
import com.jyu.common.exception.BaseException;
import com.jyu.common.result.PageResult;
import com.jyu.common.result.Result;
import com.jyu.pojo.DTO.SaveOrderDTO;
import com.jyu.pojo.VO.OrderDetailVO;
import com.jyu.pojo.VO.UserVO;
import com.jyu.pojo.entity.*;

import com.jyu.work.service.IOrderDetailService;
import com.jyu.work.service.IOrderService;
import com.jyu.work.service.IProductService;
import com.jyu.work.service.IShoppingCartService;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author guancheng
 * @since 2023-11-30
 */

@CrossOrigin(origins = "http://127.0.0.1:5173")
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IShoppingCartService shoppingCartService;

    /**
     * 订单分页查询(管理员）
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result page(int page, int pageSize) {
        IPage<Order> iPage = new Page<>();

        // 分页对象存放分页信息
        Page<Order> pageInfo = new Page(page, pageSize);
        // 新建条件查询器
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        orderService.page(pageInfo, qw);

        long total = pageInfo.getTotal();
        // 将查询的总条目数和数据集合给到 PageResult
        return Result.success(new PageResult(total, pageInfo.getRecords()), "查询成功");
    }


    /**
     * 添加订单
     *
     * @param saveOrderDTO
     * @return
     */
    @PostMapping
    public Result add(@RequestBody SaveOrderDTO saveOrderDTO) {

        Order order = new Order();
        int uuID = Math.abs(UUID.randomUUID().hashCode());
        order.setId((uuID));
        order.setOrderStatus(0);
        order.setUserId(Math.toIntExact(BaseContext.getCurrentId()));
        LocalDateTime nowTime = LocalDateTime.now();
        order.setOrderDate(nowTime);
        order.setPaymentMethod(saveOrderDTO.getPaymentMethod());
        orderService.save(order);

        ArrayList<OrderDetail> orderDetailsList = saveOrderDTO.getOrderDetailsList();
        for (int i = 0; i < orderDetailsList.size(); i++) {
            OrderDetail orderDetail = orderDetailsList.get(i);
            orderDetail.setOrderId(uuID);
            Integer productId = orderDetail.getProductId();

            Product product = productService.getById(productId);
            if (product != null) {
                orderDetail.setUnitPrice(product.getUnitPrice());
                orderDetailService.save(orderDetail);
            } else {
                throw new BaseException("无ID号为: " + productId + "商品");
            }
        }

        return Result.success(Integer.valueOf(uuID), "成功");
    }


    /**
     * 修改订单（删除订单：修改订单状态status）
     *
     * @param order
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Order order) {
        if (orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getId, order.getId())) == null) {
            return Result.success(null, "订单号不存在");
        }

        orderService.updateById(order);
        return Result.success(null, "成功");
    }


    /**
     * 支付功能：修改订单状态为1（已支付）
     *
     * @param orderId
     * @return
     */
    @PutMapping("/pay")
    @Transactional
    public Result pay(int orderId) {
        Order order = orderService.getById(orderId);
        if (order == null) {
            return Result.error("订单号不存在");
        }
        List<OrderDetail> orderDetailList = orderDetailService.list(
                new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, order.getId()));

        // 1、商品余量 - 订单所购买的数量
        for (int i = 0; i < orderDetailList.size(); i++) {
            OrderDetail orderDetail = orderDetailList.get(i);
            // 商品余量 小于 购买数量  返回余量不足
            Integer buyCount = orderDetail.getQuantity();
            // 商品信息
            Product product = productService.getById(orderDetail.getProductId());
            if (buyCount > product.getId()) {
                return Result.error(product.getName() + "余量不足");
            }
            // 商品余量大于 购买数量 正常购买update
            product.setStock(product.getStock() - buyCount);
            productService.updateById(product);
        }


        // 2、更新order状态
        LambdaUpdateWrapper<Order> uw = new LambdaUpdateWrapper<Order>().eq(Order::getId, orderId).set(Order::getOrderStatus, 1);
        orderService.update(uw);
        return Result.success(null, "支付成功");
    }


    @PutMapping("/pay4cart")
    @Transactional
    public Result pay4cart(Integer paymentMethod) {
        Long currentId = BaseContext.getCurrentId();
        // 获取当前 用户的 购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, currentId));

        // 读取用户购物车数据
        ArrayList<OrderDetail> OrderDetailsList = new ArrayList<>();
        for (int i = 0; i < shoppingCartList.size(); i++) {
            ShoppingCart shoppingCart = shoppingCartList.get(i);
            Integer productId = shoppingCart.getProductId();
            Integer quantity = shoppingCart.getQuantity();
            OrderDetail orderDetail = new OrderDetail(productId, quantity);
            OrderDetailsList.add(orderDetail);

            // 删除已读取的数据
            shoppingCartService.removeById(shoppingCart);
        }
        if (OrderDetailsList.size() > 0) {

            // 把购物车下单
            SaveOrderDTO saveOrderDTO = new SaveOrderDTO();
            saveOrderDTO.setPaymentMethod(paymentMethod);
            saveOrderDTO.setOrderDetailsList(OrderDetailsList);
                Result result = add(saveOrderDTO);

            Integer uuID = (Integer) result.getData();

            pay(uuID);

            return Result.success(null, "买空购物车");
        }

        return Result.error( "你的购物车无数据");
    }


    /**
     * 查询已支付订单
     *
     * @return
     */
    @GetMapping("/pay")
    public Result selectPays() {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getOrderStatus, 1);
        queryWrapper.eq(Order::getUserId, BaseContext.getCurrentId());
        // 当前用户已付款order订单
        List<Order> orderList = orderService.list(queryWrapper);

        List<OrderDetailVO> payDetailList = new ArrayList<>();

        // 遍历已付款order订单
        for (int i = 0; i < orderList.size(); i++) {

            Order order = orderList.get(i);

            // 一个订单里面可能保护多个商品购买信息，我们要遍历出来。
            List<OrderDetail> orderDetailList = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, order.getId()));

            for (int j = 0; j < orderDetailList.size(); j++) {
                OrderDetail orderDetail = orderDetailList.get(j);

                OrderDetailVO orderDetailVO = new OrderDetailVO();

                BeanUtils.copyProperties(order, orderDetailVO);

                BeanUtils.copyProperties(orderDetail, orderDetailVO, "id");

                Product product = productService.getById(orderDetailVO.getProductId());
                orderDetailVO.setProduct(product);

                payDetailList.add(orderDetailVO);
            }
        }

        return Result.success(payDetailList, "查询已支付订单成功");
    }


    /**
     * 查询未支付订单
     *
     * @return
     */
    @GetMapping("/unpay")
    public Result selectUnPays() {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        // 0 代表未支付的订单
        queryWrapper.eq(Order::getOrderStatus, 0);
        queryWrapper.eq(Order::getUserId, BaseContext.getCurrentId());
        // 当前用户未付款order订单
        List<Order> orderList = orderService.list(queryWrapper);

        List<OrderDetailVO> payDetailList = new ArrayList<>();

        // 遍历已付款order订单
        for (int i = 0; i < orderList.size(); i++) {

            Order order = orderList.get(i);

            // 一个订单里面可能保护多个商品购买信息，我们要遍历出来。
            List<OrderDetail> orderDetailList = orderDetailService
                    .list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, order.getId()));

            for (int j = 0; j < orderDetailList.size(); j++) {
                OrderDetail orderDetail = orderDetailList.get(j);

                OrderDetailVO orderDetailVO = new OrderDetailVO();

                BeanUtils.copyProperties(order, orderDetailVO);
                BeanUtils.copyProperties(orderDetail, orderDetailVO, "id");

                Product product = productService.getById(orderDetailVO.getProductId());
                orderDetailVO.setProduct(product);

                payDetailList.add(orderDetailVO);
            }
        }

        return Result.success(payDetailList, "未支付订单查询成功");
    }
}

